﻿using System;
using CommonUtil;
using Newtonsoft.Json.Linq;

namespace Client {
    class SocketUtil {
        private static readonly string WSURL = "ws://127.0.0.1:3000";
        private static readonly SocketUtil socket = new SocketUtil();
        readonly SocketClient socketClient = new SocketClient(WSURL);

        private SocketUtil() {
            socketClient.On("connection", SocketClient_Connection);
            socketClient.On("close", SocketClient_Close);
            socketClient.On("error", SocketClient_Error);
        }

        private object SocketClient_Error(object e) {
            var err = (Exception)e;
            LogUtil.logger.Error($"socket错误，错误原因：{err.Message}");
            return null;
        }

        private object SocketClient_Close(object arg) {
            LogUtil.logger.Info("socket已断开");
            return null;
        }

        private object SocketClient_Connection(object arg) {
            LogUtil.logger.Info("socket已连接");
            return null;
        }
        public void On(string eventName, Func<object, object> fn) {
            LogUtil.logger.Info($"添加监听器：{eventName}");
            socketClient.On(eventName, fn);
        }

        public void Emit(string eventName, JObject jObject = null) {
            LogUtil.logger.Info($"socket发送消息：{eventName}");
            socketClient.Emit(eventName, jObject);
        }

        public void Emit(string eventName, JArray jArray) {
            LogUtil.logger.Info($"socket发送消息：{eventName}");
            socketClient.Emit(eventName, jArray);
        }

        public static SocketUtil GetSocket() {
            return socket;
        }

        internal void openSocket() {
            LogUtil.logger.Info($"开始连接Socket服务器：{WSURL}");
            socketClient.Open();
        }
    }
}
